package com.store.app.activity;


import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.EventBusBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.UtilsBitmap;
import com.store.app.widget.ProgressWebView;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.json.JSONObject;

import java.io.File;
import java.util.Date;

import de.greenrobot.event.EventBus;

/**
 * 注册新门店
 */
public class WebViewRegistActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnClickListener, IOnHttpListener {


    private ImageView public_ll_return;
    private TextView tvTitle;
    private SwipeRefreshLayout sw;
    private String urls;                            //要打开的页面
    private ProgressWebView webView;
    private ProgressBar progressbar;
    private String methodReturn;                    //上传图片之后回调的方法名
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static String localTempImageFileName = "";
    private NetRequest netRequest;
    private TextView public_tv_right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_more);
        EventBus.getDefault().register(this);
        urls = getIntent().getStringExtra("url");
        Log.v("zyl", "url:" + urls);
        initView();
        setWebView();
        initData();
    }


    public void initData() {
        netRequest = new NetRequest(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_return:
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
                break;
            case R.id.public_tv_right:
                finish();
                break;
        }
    }


    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        sw = (SwipeRefreshLayout) findViewById(R.id.sw);
        sw.setOnRefreshListener(this);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        progressbar.setOnClickListener(this);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setOnClickListener(this);
        public_tv_right = (TextView) findViewById(R.id.public_tv_right);
        public_tv_right.setBackgroundResource(R.drawable.pic_icon_close_x);
        public_tv_right.setOnClickListener(this);
    }

    private void setWebView() {
        webView.clearCache(true);
        Log.v("zyl", "setWebView urls:" + urls);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // 　　//handler.cancel(); 默认的处理方式，WebView变成空白页
                handler.proceed(); // 接受证书
                // handleMessage(Message msg); 其他处理

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
                Log.v("zyl", "onReceivedError网络加载不出来");
                //停止webView的所有操作
                webView.onPause();
                webView.pauseTimers();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.v("zyl", "获取到变化的url：" + url);
                String newLayer = getValueByName(url, "newLayer");

                if (!TextUtils.isEmpty(newLayer)) {
                    if (newLayer.equals("true")) {
                        Intent intent = new Intent(WebViewRegistActivity.this, WebViewRegistActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                        return true;
                    } else {

                    }
                }

                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {

                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.startsWith("http")) {
                    urls = url;
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.v("zyl", "加载进度：" + newProgress);
                if (newProgress == 100) {
                    progressbar.setVisibility(View.GONE);
                } else {
                    if (progressbar.getVisibility() == View.GONE)
                        progressbar.setVisibility(View.VISIBLE);
                    progressbar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvTitle.setText(title);
            }
        });
        webView.getSettings().setDefaultTextEncodingName("gb2312");
        webView.addJavascriptInterface(new JSInterface(), "jsObj");
        if(Build.VERSION.SDK_INT>=21){
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            webView.loadUrl("javascript:" + methodReturn + "(" + result + ")");
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {

    }

    final class JSInterface {
        private Handler handler = new Handler();

        //上传图片
        @JavascriptInterface
        public void uploadImg(final String s) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    methodReturn = s;
                    getPic();
                }
            });
        }

        //话费充值,传递过来一个json格式的bean
        @JavascriptInterface
        public void mobileFeeRecharge(final String jsonInfo) {
            if (!TextUtils.isEmpty(jsonInfo)) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(WebViewRegistActivity.this, RechargePayActivity.class);
                        intent.putExtra("jsonInfo", jsonInfo);
                        startActivity(intent);
                    }
                }, 0);
            }
        }

        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(WebViewRegistActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        }
    }


    public void onPause() {//继承自Activity
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
        if (isFinishing()) {
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEvent(EventBusBean event) {
        if (event.type == 220) {
            webView.loadUrl(urls);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        Log.v("zyl", "下拉刷新了");
//        setWebView();
        webView.loadUrl(urls);
        sw.setRefreshing(false);
    }


    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    public void getPic() {
        new AlertDialog.Builder(WebViewRegistActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }

                            }
                        }).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                CropUtils.startCropActivity(uri, WebViewRegistActivity.this, 2, 1);
            }
        }
        //拍照
        else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {

            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            CropUtils.startCropActivity(uri, WebViewRegistActivity.this, 2, 1);
        }
        //裁剪成功
        else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                BitmapBean bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);

                if (bitmapBean.getIsBm() != null) {

                    netRequest.requestUploadPic(1, bitmapBean.getIsBm());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            //剪切失败
            Toast.makeText(WebViewRegistActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
